package com.atguigu.gmall.realtime.dwd.db.split.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.common.base.BaseApp;
import com.atguigu.gmall.realtime.common.bean.TableProcessDwd;
import com.atguigu.gmall.realtime.common.constant.Constant;
import com.atguigu.gmall.realtime.common.util.FlinkSinkUtil;
import com.atguigu.gmall.realtime.common.util.FlinkSourceUtil;
import com.atguigu.gmall.realtime.common.util.JDBCUtil;
import com.atguigu.gmall.realtime.dwd.db.split.function.BaseDbTableProcessFunction;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import org.apache.doris.shaded.org.apache.thrift.TBase;
import org.apache.doris.shaded.org.apache.thrift.TException;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;

import java.sql.Connection;

public class DwdBaseDb extends BaseApp {
    public static void main(String[] args) {
        new DwdBaseDb().start(10019,
                4,
                "dwd_base_db",
                Constant.TOPIC_DB
        );

    }
    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> kafkaStrDS) {
        // 对流中数据kafkaStrDS进行类型转换以及ETL jsonStr -> jsonObj
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaStrDS.process(
                new ProcessFunction<String, JSONObject>() {
                    @Override
                    public void processElement(String jsonStr, ProcessFunction<String, JSONObject>.Context context, Collector<JSONObject> collector) throws Exception {
                        try {
                            JSONObject jsonObj = JSON.parseObject(jsonStr);
                            String type = jsonObj.getString("type");
                            if (!type.startsWith("bootstrap")) {
                                collector.collect(jsonObj);
                            }
                        } catch (Exception e) {
                            System.out.println("数据不是标准json");
                        }
                    }
                }

        );
        //jsonObjDS.print();
        // 使用FlinkCDC获取配置表信息
        // 创建MySQLSource对象
        MySqlSource<String> mysqlSource = FlinkSourceUtil.getMysqlSource("gmall0221_config", "table_process_dwd");
        // 读取数据 封装为流
        DataStreamSource<String> mysqlStrDS = env.fromSource(mysqlSource, WatermarkStrategy.noWatermarks(), "mysql_source").setParallelism(1);
        //mysqlStrDS.print();
        // 对flinkCDC读取到数据进行类型转换 jsonStr -> 实体类对象
        SingleOutputStreamOperator<TableProcessDwd> tsDS = mysqlStrDS.map(
                new MapFunction<String, TableProcessDwd>() {
                    @Override
                    public TableProcessDwd map(String jsonStr) throws Exception {
                        JSONObject jsonObj = JSON.parseObject(jsonStr);
                        String op = jsonObj.getString("op");
                        TableProcessDwd tableProcessDwd = null;
                        if ("d".equals(op)){
                            tableProcessDwd = jsonObj.getObject("before" , TableProcessDwd.class);
                        } else {
                            tableProcessDwd = jsonObj.getObject("after" , TableProcessDwd.class);
                        }
                        tableProcessDwd.setOp(op);
                        return tableProcessDwd;
                    }
                    
                }
        );
        // 广播配置流 -- broadcast
        MapStateDescriptor<String, TableProcessDwd> mapStateDescriptor 
                = new MapStateDescriptor<String, TableProcessDwd>("mapStateDescriptor" , String.class, TableProcessDwd.class);
        BroadcastStream<TableProcessDwd> broadcastDS = tsDS.broadcast(mapStateDescriptor);
        // 关联主流业务数据以及广播流配置信息 -- connect
        BroadcastConnectedStream<JSONObject, TableProcessDwd> connectDS = jsonObjDS.connect(broadcastDS);
        // 对关联后的数据进行处理 -- process
        SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDwd>> realDS = connectDS.process(new BaseDbTableProcessFunction(mapStateDescriptor));
        // 将数据同步到kafka对应的主题中
        realDS.print();
        realDS.sinkTo(FlinkSinkUtil.getKafkaSink());
    }
}  
